import os

from alipay import AliPay, AliPayConfig
from django.http import JsonResponse
from django.shortcuts import render
# Create your views here.
from django.views import View

from apps.orders.models import OrderInfo
from apps.payment.models import Payment
from meiduo_mall import settings


class PaymentStatusView(View):
    """保存订单支付结果"""

    def put(self,request):
        query_dict = request.GET
        data = query_dict.dict()
        signature = data.pop('sign')

        app_private_key_string = open(settings.APP_PRIVATE_KEY_PATH).read()
        alipay_public_key_string = open(settings.ALIPAY_PUBLIC_KEY_PATH).read()

        # 创建支付宝支付对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_private_key_string=app_private_key_string,
            alipay_public_key_string=alipay_public_key_string,
            app_notify_url=None,  # 默认回调url
            sign_type="RSA2",
            debug=True,
            config=AliPayConfig(timeout=15)
        )
        success = alipay.verify(data,signature)
        if success:
            # 获取 trade_no	String	必填	64	支付宝交易号
            trade_no=data.get('trade_no')
            order_id=data.get('out_trade_no')
            Payment.objects.create(
                trade_id=trade_no,
                order_id=order_id
            )
            OrderInfo.objects.filter(order_id=order_id).update(status=OrderInfo.ORDER_STATUS_ENUM['UNSEND'])

            return JsonResponse({'code': 0, 'errmsg': 'ok', 'trade_id': trade_no})
        else:

            return JsonResponse({'code': 400, 'errmsg': '请到个人中心的订单中查询订单状态'})

